package com.sunday.haowushop.adapter;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.lzy.ninegrid.ImageInfo;
import com.lzy.ninegrid.NineGridView;
import com.lzy.ninegrid.preview.NineGridViewClickAdapter;
import com.sunday.common.utils.DeviceUtils;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.StreamUtil;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.utils.download.ImgUtils;
import com.sunday.common.widgets.BetterRecyclerView;
import com.sunday.common.widgets.CircleImageView;
import com.sunday.haowushop.R;
import com.sunday.haowushop.common.AppConfig;
import com.sunday.haowushop.common.BaseApp;
import com.sunday.haowushop.entity.FindItem;
import com.sunday.haowushop.http.ApiClient;
import com.sunday.haowushop.http.AppOperator;
import com.sunday.haowushop.ui.MainActivity;
import com.sunday.haowushop.ui.ShowBigImage;
import com.sunday.haowushop.ui.find.FindItenDetailActivity;
import com.sunday.haowushop.ui.product.ProductDetailsActivity;
import com.sunday.haowushop.widgets.ShareWindow;

import java.io.File;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

import butterknife.Bind;
import butterknife.ButterKnife;

import static android.content.Context.CLIPBOARD_SERVICE;


/**
 * Created by 刘涛 on 2017/4/17.
 */

public class FindListAdapter extends RecyclerView.Adapter {


    private Context mContext;
    private List<FindItem> dataSet;
    private ClipboardManager myClipboard;
    private int appWidth;

    public FindListAdapter(Context context, List<FindItem> datas) {
        mContext = context;
        dataSet = datas;
        appWidth = DeviceUtils.getDisplay(mContext).widthPixels;
        myClipboard = (ClipboardManager) mContext.getSystemService(CLIPBOARD_SERVICE);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.list_find_item, null);
        return new ListHolder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        ListHolder listHolder = (ListHolder) holder;
        FindItem item = dataSet.get(position);
//        if (!TextUtils.isEmpty(item.getImage())) {
//            Glide.with(mContext)
//                    .load(item.getImage())
//                    .error(R.mipmap.ic_default)
//                    .into(listHolder.contentImg);
//        }


        if (!TextUtils.isEmpty(item.getImage())) {
            Glide.with(mContext)
                    .load(item.getImage())
                    .error(R.mipmap.ic_default)
                    .into(listHolder.circleImg);
        }
        listHolder.title.setText(item.getName());
        listHolder.time.setText(item.getCreateTime());
        listHolder.contentTitle.setText(item.getTitle());
        listHolder.content.setText(item.getSummary());

        ArrayList<ImageInfo> imageInfo = new ArrayList<>();
        List<String> imageDetails = item.getImages();
        if (imageDetails != null) {
            for (String imageDetail : imageDetails) {
                ImageInfo info = new ImageInfo();
                info.setThumbnailUrl(imageDetail);
                info.setBigImageUrl(imageDetail);
                imageInfo.add(info);
            }
        }
        listHolder.imgGridView.setAdapter(new NineGridViewClickAdapter(mContext, imageInfo));
        listHolder.imgGridView.setSingleImageSize(appWidth);
        listHolder.imgGridView.setSingleImageRatio(2);

        if (item.getStatus() == 0) {
            listHolder.titleFrom.setText("平台");
            listHolder.titleFrom.setBackgroundResource(R.drawable.shape_blue_stroke);
            listHolder.titleFrom.setTextColor(Color.parseColor("#399efb"));
        } else {
            listHolder.titleFrom.setText("用户精选");
            listHolder.titleFrom.setBackgroundResource(R.drawable.shape_red_stroke);
            listHolder.titleFrom.setTextColor(Color.parseColor("#ef0022"));
        }

        listHolder.totalLayout.setTag(item);
        listHolder.btnSave.setTag(item);
        listHolder.btnShare.setTag(item);

    }

    @Override
    public int getItemCount() {
        return dataSet.size();
    }

    String filePath;
    Bitmap saveBitmap;

    class ListHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        @Bind(R.id.circle_img)
        CircleImageView circleImg;
        @Bind(R.id.title)
        TextView title;
        @Bind(R.id.title_from)
        TextView titleFrom;
        @Bind(R.id.time)
        TextView time;
        @Bind(R.id.layout_head)
        RelativeLayout layoutHead;
        @Bind(R.id.content_title)
        TextView contentTitle;
        @Bind(R.id.content)
        TextView content;
        @Bind(R.id.view)
        View view;
        @Bind(R.id.total_layout)
        RelativeLayout totalLayout;
        @Bind(R.id.btn_save)
        TextView btnSave;
        @Bind(R.id.btn_share)
        TextView btnShare;
        @Bind(R.id.img_grid_view)
        NineGridView imgGridView;


        public ListHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            totalLayout.setOnClickListener(this);
            btnSave.setOnClickListener(this);
            btnShare.setOnClickListener(this);

        }

        @Override
        public void onClick(View v) {
            FindItem item = (FindItem) v.getTag();
            switch (v.getId()) {
                case R.id.btn_save:
                    if (item.getImages() == null) {
                        return;
                    }
                    if (item.getImages().isEmpty()) {
                        return;
                    }

                    ClipData myClip = ClipData.newPlainText("text", item.getDesc());
                    myClipboard.setPrimaryClip(myClip);
                    for (String img : item.getImages()) {
                        final Future<File> future = Glide.with(mContext)
                                .load(img)
                                .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
                        AppOperator.runOnThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    File sourceFile = future.get();
                                    if (sourceFile == null || !sourceFile.exists())
                                        return;
                                    String extension = ImgUtils.getExtension(sourceFile.getAbsolutePath());
                                    String extDir = AppConfig.DEFAULT_SAVE_IMAGE_PATH;
                                    File extDirFile = new File(extDir);
                                    if (!extDirFile.exists()) {
                                        if (!extDirFile.mkdirs()) {
                                            // If mk dir error
                                            callSaveStatus(false, null);
                                            return;
                                        }
                                    }
                                    final File saveFile = new File(extDirFile, String.format("IMG_%1$s%2$s.%3$s", System.currentTimeMillis(), MD5Utils.random(), extension));
                                    final boolean isSuccess = StreamUtil.copyFile(sourceFile, saveFile);
                                    callSaveStatus(isSuccess, saveFile);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    callSaveStatus(false, null);
                                }
                            }
                        });
                    }

                    break;
                case R.id.btn_share:
                      /*1我要开店2分享店铺3普通商品4限时购商品)-memberId(会员Id)-productId(商品Id)-limitId(限时购时间段Id)
                    这四个参数没有值的传0
                    例如普通商品分享：http://weixin.zj-yunti.com/authorizationPage.html?param=3-1-14-0*/
                    long memberId = BaseApp.getInstance().getMember().getId();
                    String shareUrl = String.format("%1$s%2$d-%3$d-%4$d-%5$d", ApiClient.SHARE_URL, 3, memberId, item.getRefId(), 0);
                    ShareWindow shareWindow = new ShareWindow(mContext, shareUrl, item.getName(), item.getProductImage(),
                            String.format("%s", item.getScale().setScale(2, RoundingMode.HALF_UP)),
                            mContext.getResources().getString(R.string.share_product_desc), String.format("%s", item.getCurrentPrice().setScale(2, RoundingMode.HALF_UP)),item.getShareImage());
                    shareWindow.showPopupWindow(btnShare);
                    break;
                case R.id.total_layout:
//                    Intent intent = new Intent(mContext, ProductDetailsActivity.class);
//                    intent.putExtra("productName", item.getName());
//                    intent.putExtra("productId", item.getRefId());
//                    intent.putExtra("productImg", item.getProductImage());
//                    intent.putExtra("productPrice", String.format("%s", item.getCurrentPrice().setScale(2, RoundingMode.HALF_UP)));
//                    intent.putExtra("scale", String.format("%s", item.getScale().setScale(2, RoundingMode.HALF_UP)));
//                    intent.putExtra("type", 1);//类型(1-普通商品 2-限时购)
                    Intent intent = new Intent(mContext, FindItenDetailActivity.class);
                    intent.putExtra("findItem", item);
                    mContext.startActivity(intent);
                    break;
            }
        }
    }

    private void callSaveStatus(final boolean success, final File savePath) {
        ((MainActivity) mContext).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (success) {
                    // notify
                    Uri uri = Uri.fromFile(savePath);
                    mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                    Log.i("img_name------", String.valueOf(savePath));
                    ToastUtils.showToast(mContext, "图文保存成功");
                } else {
                    ToastUtils.showToast(mContext, "图片保存失败");
                }
            }
        });
    }

    class ImageAdapter extends RecyclerView.Adapter {

        private List<String> dataSet = new ArrayList<>();

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.list_find_img_item, null);
            RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(appWidth * 5 / 6, ViewGroup.LayoutParams.WRAP_CONTENT);
            view.setLayoutParams(layoutParams);
            return new ImgHolder(view);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            ImgHolder imgHolder = (ImgHolder) holder;
            if (!TextUtils.isEmpty(dataSet.get(position))) {
                Glide.with(mContext)
                        .load(dataSet.get(position))
                        .placeholder(R.mipmap.ic_default)
                        .error(R.mipmap.ic_default)
                        .into(imgHolder.imageView);
            }
            imgHolder.imageView.setTag(R.id.image, dataSet.get(position));
        }

        @Override
        public int getItemCount() {
            return dataSet.size();
        }

        public void setDataSet(List<String> dataSet) {
            this.dataSet = dataSet;
        }

        class ImgHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            ImageView imageView;
            LinearLayout layout;


            public ImgHolder(View itemView) {
                super(itemView);
                imageView = (ImageView) itemView.findViewById(R.id.image);
                layout = (LinearLayout) itemView.findViewById(R.id.linearLayout);
                imageView.setOnClickListener(this);
            }

            @Override
            public void onClick(View v) {
                String img = (String) v.getTag(R.id.image);
                Intent intent = new Intent(mContext, ShowBigImage.class);
                intent.putStringArrayListExtra("data", (ArrayList<String>) dataSet);
                mContext.startActivity(intent);
            }
        }
    }


}
